package com.tree.common.dto;

import com.alibaba.fastjson.JSON;
import com.tree.common.enums.ResultCode;
import com.tree.common.util.TraceContextHolder;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * @ClassName com.tree.common.dto
 * Description: <类功能描述>. <br>
 * <p>
 * 通用返回对象Result
 * </p>
 * @Author tree
 * @Date 2020-03-28 23:48
 * @Version 1.0
 */
@Data
@Accessors(chain = true)
public class Result <T> implements Serializable {

    private static final long serialVersionUID = 1L;
    @ApiModelProperty(value = "结果编码", dataType = "int", required = true)
    private int code;

    @ApiModelProperty(value = "结果消息", dataType = "String", required = true)
    private String message;

    @ApiModelProperty(value = "返回对象", required = true)
    private T data;

    private String traceId;


    public static Result success(){
        return new Result().setCode(ResultCode.SUCCESS.getCode()).setMessage(ResultCode.SUCCESS.getMessage())
                .setTraceId(TraceContextHolder.getCurrentTraceId());
    }

    public static Result success(Object data){
        return new Result().setCode(ResultCode.SUCCESS.getCode()).setMessage(ResultCode.SUCCESS.getMessage())
                .setData(data).setTraceId(TraceContextHolder.getCurrentTraceId());
    }

    public static Result fail(ResultCode resultCode){
        return new Result().setCode(resultCode.getCode()).setMessage(resultCode.getMessage())
                .setTraceId(TraceContextHolder.getCurrentTraceId());
    }

    public static Result fail(int code,String message){
        return new Result().setCode(code).setMessage(message)
                .setTraceId(TraceContextHolder.getCurrentTraceId());
    }


    public static Result fail(ResultCode resultCode, Object data){
        return new Result().setCode(resultCode.getCode()).setMessage(resultCode.getMessage())
                .setData(data).setTraceId(TraceContextHolder.getCurrentTraceId());
    }

    public static Result fail(int code,String message, Object data){
        return new Result().setCode(code).setMessage(message).setData(data)
                .setTraceId(TraceContextHolder.getCurrentTraceId());
    }

    public static void main(String[] args) {
        System.out.println(JSON.toJSONString(Result.success(1)));
        System.out.println(JSON.toJSONString(Result.fail(ResultCode.PARAM_IS_INVALID)));
    }


}
